<?php

namespace app\admin\controller;

use app\admin\model\ZoneList;
use app\common\controller\Backend;
use think\Db;
use think\Exception;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Model;
use think\response\Json;

/**
 * 会员管理
 *
 * @icon fa fa-anchor
 */
class Anchor extends Backend
{

    /**
     * Anchor模型对象
     * @var \app\admin\model\Anchor
     */
    protected $model = null;
    protected $zone = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Anchor;
        $this->zone = new ZoneList();

        $zoneList = $this->zone->all();
        $zoneData = [];
        foreach ($zoneList as $z) {
            $zoneData[$z->zone] = $z->zonename;
        }

        $grade = Db::table('user_right_config')->order("grade", "asc")->select();

        $gradeData = [];
        foreach ($grade as $v) {
            $data = [];
            $data['id'] = $v['grade'];
            $data['name'] = $v['gradeName'];

            $gradeData[] = $data;
        }

        $this->assignconfig("grade", $gradeData);
        $this->assign("grade", $gradeData);
        $this->assignconfig("zoneList", $zoneData);
        $this->assign("zoneList", $zoneData);
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {

            $zone = new ZoneList();

            $this->assign("online", $this->model->where([
                'status' => 1
            ])->count());
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();

        $where = json_decode($this->request->get("filter", ''), true);
        if (isset($where['zone_list.zonename']) && !empty($where['zone_list.zonename'])) {
            $where['zone_list.zone'] = $where['zone_list.zonename'];
            unset($where['zone_list.zonename']);
        }

        if (isset($where['user_right_config.gradeName'])) {
            $where['user_right_config.grade'] = $where['user_right_config.gradeName'];
            unset($where['user_right_config.gradeName']);
        }

        if (isset($where['createtime']) && !empty($where['createtime'])) {
            $time = explode(" - ", $where['createtime']);
            $where['createtime'] = ['between', [strtotime($time[0]), strtotime($time[1])]];
        }

        $list = $this->model
            ->with(['zoneList', 'userRightConfig'])
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
//echo $this->model->getLastSql();die;
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    public function setting()
    {
        if (false === $this->request->isPost()) {
            $data = [
                'forGirlOne' => '',
                'forGirlTwo' => '',
                'forBoyOne' => '',
                'forBoyTwo' => ''
            ];

            $this->assign('row', $data);
            return $this->view->fetch();
        }

        //设置过滤方法
        $params = $this->request->post('row/a');


        for ($i = 1; $i <= 4; $i++) {
            $data = [
                'zone' => $params['zone'],
                'speakType' => $i,
                'speakID' => '',
                'speakDefault' => '',
                'speakLocal' => $params[$i . 'speakLocal'],
                'cmd' => 1
            ];

            $must_param = [
                "zone",
                "speakType",
                'speakID',
                'speakDefault',
                'speakLocal',
                'cmd'
            ];
            foreach ($must_param as $v) {
                if ((!isset($data[$v]) || empty($data[$v])) && ($v != 'speakID' && $v != 'speakDefault')) {
                    $this->error($v . '-是必传参数');
                }
            }

            $keywordArr = explode("\r\n", $params[$i . 'speakLocal']);
            foreach ($keywordArr as $arr) {
                $procedure_name = 'speak_list_set';
                $data['speakDefault'] = $arr;
                $rs = $this->model->procedure_data_add($data, $must_param, $procedure_name);
            }
        }

        return $this->success();
    }

    public function getSetting()
    {
        $id = request()->get('id');
        if ($id != 0) {
            $data = [];
            for ($i = 1; $i <= 4; $i++) {
                //设置过滤方法
                $params = $this->request->get();
                $params['speakType'] = $i;
                $params['speakIn'] = '';
                $must_param = [
                    "id",
                    "speakType",
                    "speakIn"
                ];

                $out_column = [
                    "speakLocal",
                ];
                //查询
                $procedure_name = 'speak_list_get';
                $list = $this->model->procedure_data_select($params, $must_param, $procedure_name, $out_column);

                if (!empty($list)) {
                    if ($i == 1) {
                        $data['forGirlOne'] = $list[0]['speakLocal'];
                    } elseif ($i == 2) {
                        $data['forGirlTwo'] = $list[0]['speakLocal'];
                    } elseif ($i == 3) {
                        $data['forBoyOne'] = $list[0]['speakLocal'];
                    } elseif ($i == 4) {
                        $data['forBoyTwo'] = $list[0]['speakLocal'];
                    }
                }
            }

            $this->success("操作成功", "", $data);
        }
    }

    public function hot_setting()
    {
        if (false === $this->request->isPost()) {


            $sql = "SELECT fansInterval,fansMaxTask,videoInterval,videoMaxTask,videoMaxLikes,videoMaxSpeak,roomInterval,roomMaxTask,roomSpeakInterval FROM heatrobot_set where robotuser = ''";
            $data = Db::query($sql);
            if (!empty($data)) {
                $this->assign('data', $data[0]);
            } else {
                $data = [
                    'fansInterval' => '',
                    'fansMaxTask' => '',
                    'videoInterval' => '',
                    'videoMaxTask' => '',
                    'videoMaxLikes' => '',
                    'videoMaxSpeak' => '',
                    'roomInterval' => '',
                    'roomMaxTask' => '',
                    'roomSpeakInterval' => '',
                ];
                $this->assign('data', $data);
            }

            return $this->view->fetch();
        }

        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();

        try {
            $sql = "call robot_param_set('', '" . $params['fansInterval'] . "', '" . $params['fansMaxTask'] . "', '"
                . $params['videoInterval'] . "', '" . $params['videoMaxTask'] . "', '" . $params['videoMaxLikes'] . "', '"
                . $params['videoMaxSpeak'] . "', '" . $params['roomInterval'] . "', '" . $params['roomMaxTask']
                . "', '" . $params['roomSpeakInterval'] . "', @_res)";

            Db::query($sql);
            Db::commit();
            $result = true;
        } catch (ValidateException | PDOException | Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    public function setLevel()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {

            $this->assign('id', request()->get("id"));
            return $this->view->fetch();
        }

        //设置过滤方法
        $params = $this->request->post('row/a');
        $must_param = [
            'userName',
            'grade',
            'cutoffdates',
        ];

        foreach ($must_param as $v) {
            if ($v != 'grade') {
                if (!isset($params[$v]) || empty($params[$v])) {
                    $this->error($v . '-是必传参数');
                }
            }
        }
        $procedure_name = 'usergrade_update';
        $rs = $this->model->procedure_data_add($params, $must_param, $procedure_name);
        if ($rs['res']) {
            $this->success();
        } else {
            $this->error($this->model->getError());
        }
    }

    public function searchUser()
    {
        $id = request()->get('id');

        $data = Db::table('user')->where([
            'username' => $id
        ])->find();

        if (!$data)
            $this->error("没有找到用户");

        $this->success("操作成功", null, $data);
    }

    public function boxinfo()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {

            $this->assign('total', Db::table('task_box_log')->where(['robotUser' => request()->get("robotUser")])->sum('getDiamonds'));
            return $this->view->fetch();
        }

        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $where = json_decode($this->request->get("filter", ''), true);
        if (isset($where['recordTime']) && !empty($where['recordTime'])) {
            $time = explode(" - ", $where['recordTime']);
            $where['recordTime'] = ['between', [$time[0], $time[1]]];
        }

        if (!empty(request()->get("robotUser"))) {
            $where['robotUser'] = request()->get("robotUser");
        }

        $list = Db::table('task_box_log')
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
//echo Db::getLastSql();die;
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }
}
